package com.quanyan.stadiumScheduler.biz.impl;

import com.google.common.collect.Lists;
import com.quanyan.stadiumScheduler.constants.GameConstants;
import com.quanyan.stadiumScheduler.biz.BizGameOrderDao;
import com.quanyan.stadiumScheduler.entity.*;
import com.quanyan.stadiumScheduler.mapper.TbGameEventTeamMapper;
import com.quanyan.stadiumScheduler.mapper.TbGameOrderMapper;
import com.quanyan.stadiumScheduler.mapper.TbTeamDoubleAddendumMapper;
import com.quanyan.stadiumScheduler.mapper.VStadiumUserDefinedMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: zyq
 * Date: 2016/7/6 0006
 * Time: 16:33
 */

@Service
public class BizGameOrderDaoImpl implements BizGameOrderDao {

    @Autowired
    TbGameOrderMapper gameOrderMapper;

    @Autowired
    TbGameEventTeamMapper gameEventTeamMapper;

    @Autowired
    VStadiumUserDefinedMapper userDefinedMapper;

    @Autowired
    TbTeamDoubleAddendumMapper tbTeamDoubleAddendumMapper;

    @Override
    @Transactional(rollbackFor=Exception.class)
    public Integer clearExpireOrder() {
        TbGameOrderExample example = new TbGameOrderExample();
        TbGameOrderExample.Criteria criteria = example.createCriteria();
        /**
         * 1.未完结
         * 2.支付状态：待支付
         * 3.订单状态：支付期间
         */
        criteria.andIsCloseEqualTo(GameConstants.ORDER_IS_CLOST_NO);
        criteria.andOrderStatusEqualTo(GameConstants.WAIT_ORDER);
        criteria.andPayWaitEqualTo(GameConstants.ON_PAYING);
        criteria.andDeadTimeLessThan(new Date());
        List<TbGameOrder> gameOrders = gameOrderMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(gameOrders)){
            //说明有过期订单
            List<Integer> list = Lists.newArrayList();
            for(TbGameOrder order :gameOrders){
                list.add(order.getGameEventId());
            }
            restoreShorage(list);
            TbGameOrder tbGameOrder = new TbGameOrder();
            tbGameOrder.setIsClose(GameConstants.ORDER_IS_CLOST_YES);
            tbGameOrder.setOrderStatus(GameConstants.EXPIRE_ORDER);
            tbGameOrder.setPayWait(GameConstants.FAIL_PAY);
            return gameOrderMapper.updateByExampleSelective(tbGameOrder,example);
        }
        return 0;
    }


    public Integer restoreShorage(List<Integer> ids){
        return userDefinedMapper.restoreStadiumAmount(ids,1);
    }


}
